package cn.njupt.edu.sw.javamail_web.mail.web.servlets;

import java.io.IOException;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SendMailServlet
 */
@WebServlet(description = "发送邮件的servlet", urlPatterns = { "/SendMailServlet" })
public class SendMailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Context initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			Session session = (Session) envCtx.lookup("mail/Session");
			session.setDebug(true);
		
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("shiweideyouxiang@sina.cn"));
			InternetAddress to[] = new InternetAddress[1];
			to[0] = new InternetAddress("1551308762@qq.com");
			message.setRecipients(Message.RecipientType.TO, to);
			message.setSubject("中文");
			//需要指明charset=GB2312/GBK,否则会出现乱码
			message.setContent("中文", "text/plain;charset=GB2312");
			Transport transport=session.getTransport();
			transport.connect("smtp.sina.cn", 25, "shiweideyouxiang@sina.cn",
					"1551308762qwe");
			transport.sendMessage(message, to);
			transport.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
